package com.hoan.client;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.hoan.service.IOrderManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @BindView(R.id.tv_call)
    TextView tv_call;

    private boolean connected;
    private IOrderManager mIOrderManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        Intent intent = new Intent();
        intent.setAction("com.hoan.service.OrderService");
        intent.setPackage("com.hoan.service");
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mIOrderManager = IOrderManager.Stub.asInterface(service);
            connected = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mIOrderManager = null;
            connected = false;
        }
    };

    @OnClick({R.id.tv_call})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_call:
                Log.i(TAG, "connected: " + connected);
                if (!connected) {
                    Toast.makeText(MainActivity.this, "远程服务已断开连接", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    int result = mIOrderManager.add(1, 5);
                    Toast.makeText(MainActivity.this, "和：" + result, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "result: " + result);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (connected) {
            unbindService(mServiceConnection);
        }
    }
}